###Replication file: Rozas-Bugueño, Joaquín. 
###Between hope and disaffection: the Chilean Constitution-Making 
###and the intermediation crisis.
###PS: Political Science & Politcs. Politics Symposium, 
###Constitution-Making in the 21st Century

###To replicate the results regarding the article “Betweeen Hope and Disaffection: 
###the Chilean Constitution-Making and the Intermediation Crisis,” 
###it is necessary to download the software R from 
###R Project: https://www.r-project.org/ 

###0. Outline of the replication
###1. Interviewees' description
###2. Analysis with the Chilean Constitutional Convention Delegates' Trajectories Dataset
###3. Analysis with the COES' ELSOC Survey
###4. Appendix

###1. interviewees' description----

###1.1 Constructing a dataset of the interviewees' characteristics
Districts <- c("North","Center","Metropolitan Region","South")
Delegates <- c(2,6,6,5) 
Candidates <- c(2,1,3,0) 
Women <- c(4,5,3,3) 
Men <-  c(0,2,6,2)
Militants <- c(1,2,4,1)
Independents <- c(3,5,5,4) 
Yes <- c(4,6,8,4) 
No <- c(0,1,1,1)
Total <- c(4,7,9,5)

df_int <- data.frame(Districts, Delegates, Candidates, Women, Men, Militants,
                     Independents, Yes, No, Total)

###Loading package required for constructing the dataset in long format
library("tidyr")

df_long <- df_int %>%
  gather(Category, Frequency, -Districts, -Total)

df_long$facet[df_long$Category=="Delegates"|df_long$Category=="Candidates"] <- "Relation with the Convention"
df_long$facet[df_long$Category=="Women"|df_long$Category=="Men"] <- "Sex"
df_long$facet[df_long$Category=="Militants"|df_long$Category=="Independents"] <- "Party affiliation"
df_long$facet[df_long$Category=="Yes"|df_long$Category=="No"] <- "Civic volunteer organization membership"

str(df_long$facet)
df_long$facet <- factor(df_long$facet,
                        levels = c("Relation with the Convention",
                                   "Sex",
                                   "Party affiliation",
                                   "Civic volunteer organization membership"))

###1.2. Plot the interviewees' characteristics
###Loading packages required to plot
library("ggplot2")

ggplot(df_long, aes(x = Districts, y = Frequency, fill = Category)) +
  geom_bar(stat = "identity", position = "stack") +
  labs(x = "Districts' geographical zone", y = "Number of interviewees") +
  scale_fill_manual(
    name = "Category",
    values = c("Delegates" = "#ADD8E6","Candidates" = "#FFB6C1",
               "Women" = "#FFFFCC", "Men" = "#DCD0FF",
               "Militants" = "#A0DAA9","Independents" = "#FFD3D3",
               "Yes" = "#B0E0E6","No" = "#FFDAB9"),
    breaks = c("Delegates", "Candidates", 
               "Women", "Men", 
               "Militants", "Independents", 
               "Yes", "No")) +
  ylim(0, 10) +
  scale_y_continuous(breaks = seq(0, 10, by = 1)) +
  theme(text = element_text(size = 12),
        axis.title.y = element_text(size = 12),
        axis.title.x = element_text(size = 12),
        legend.title = element_text(size = 10),
        legend.text = element_text(size = 10),
        legend.key.height = unit(0.15, 'cm'),
        legend.key.width = unit(0.15, 'cm')) +
  ggtitle("Figure 1. Sample of interviewees’ description") +
  labs(caption = "Source: Author's own elaboration") + 
  theme(plot.caption = element_text(hjust=0)) +
  facet_wrap(~facet, ncol = 2)

###2. Analysis with the Chilean Constitutional Convention delegates' trajectories dataset----

###Upload the dataset
###Loading package required for opening Excel dataframe from Harvard Dataverse website
library("readxl")
library("httr")

url <- "https://drive.google.com/uc?id=1u8aBOljuqfBlsdhXh3cAGeq6Xl4-IJUJ"

# Descargar el archivo
download.file(url, "CC_delegates_dataset.xlsx", mode = "wb")
CC <- read_excel("CC_delegates_dataset.xlsx")

###2.1. Preparing the dataframe for analysis
###Recodification of variables

library("dplyr")

###Political ties' profile
str(CC$pol_ties)
CC$pol_ties <- as.factor(CC$pol_ties)
table(CC$pol_ties)
CC$pol_ties <- factor(CC$pol_ties, 
                    levels=c("Partisan militant",
                             "Partisan independent",
                             "Non-partisan independent"))

###Recoding Social organization's main demand variable based on
###the COES' Observatory of Conflicts' categorization of demands
str(CC$recfin_dem1org1)
CC$recfin_dem1org1 <- as.factor(CC$recfin_dem1org1)
table(CC$recfin_dem1org1)

CC$demands <- dplyr::recode_factor(CC$recfin_dem1org1,
                                   "Sport" = "Culture",
                                   "Disability Rights" = "Health")

###Creating new variable with the recodification of the social organizations' demands
CC$demands <- factor(CC$demands, 
                     levels=c("Religion",
                              "Indigenous People",
                              "Environmental",
                              "Culture",
                              "Human Rights",
                              "Education",
                              "Feminist",
                              "Labor",
                              "LGTBIQ+",
                              "Regionalist",
                              "Health"))

table(CC$demands)

###Creation of new variable with synthetized categorization of the regions of the
###delegates' electoral districts
table(CC$region)
str(CC$region)
CC$RM <- as.factor(CC$region) ###the name of the variable is related to the Metropolitan Region of Chile (RM in Spanish)
CC$RM <- dplyr::recode_factor(CC$RM, 
                              "Metropolitana" = "Metropolitan Region",
                              "No region" = "Indigenous People",
                              "IV - V - RM - VI - VII regions" = "Indigenous People",
                              "VIII - IX - XVI regions" = "Indigenous People",
                              "X - XI - XIV regions" = "Indigenous People",
                              .default = "Other regions")

CC$RM <- factor(CC$RM, 
                levels=c("Metropolitan Region",
                         "Other regions",
                         "Indigenous People"))

table(CC$RM)

###New variable with the recodification of the delegates' electoral districts
table(CC$district)
str(CC$district)
CC$district <- as.factor(CC$district)
CC$district_rec <- dplyr::recode_factor(CC$district,
                                        "1" = "D1", "2" = "D2", "3" = "D3",
                                        "4" = "D4", "5" = "D5", "6" = "D6",
                                        "7" = "D7", "8" = "D8", "9" = "D9",
                                        "10" = "D10", "11" = "D11", "12" = "D12",
                                        "13" = "D13", "14" = "D14", "15" = "D15",
                                        "16" = "D16", "17" = "D17", "18" = "D18",
                                        "19" = "D19", "20" = "D20", "21" = "D21",
                                        "22" = "D22", "23" = "D23", "24" = "D24",
                                        "25" = "D25", "26" = "D26", "27" = "D27",
                                        "28" = "D28",
                                        "mapuche" = "Mapuche",
                                        "aimara" = "Other Indigenous People",
                                        "atacameño" = "Other Indigenous People",
                                        "chango" = "Other Indigenous People",
                                        "colla" = "Other Indigenous People",
                                        "diaguita" = "Other Indigenous People",
                                        "kawashkar" = "Other Indigenous People",
                                        "quechua" = "Other Indigenous People",
                                        "rapanui" = "Other Indigenous People",
                                        "yagán" = "Other Indigenous People")
table(CC$district_rec)

###Creation of a new variable with recodification of delegates' educational level
str(CC$educ_level)
table(CC$educ_level)

CC$educ_rec <- dplyr::recode_factor(CC$educ_level,
                                    "Complete doctorate degree" = "Postgraduate",
                                    "Complete master degree" = "Postgraduate",
                                    .default = "Less than postgraduate")
table(CC$educ_rec)

###Delegates' sex variable
table(CC$sex)
str(CC$sex)
CC$sex <- as.factor(CC$sex)

###Creation of a new delegates' marital status variable 
table(CC$mar_stat)
str(CC$mar_stat)
CC$mar_stat <- as.factor(CC$mar_stat)
CC$married <- dplyr::recode_factor(CC$mar_stat,
                                   "Married" = "Married",
                                   "Domestic partner" = "Not married",
                                   "Divorced" = "Not married",
                                   "Single" = "Not married")
table(CC$married)

###2.2. Plot Figure 2: Delegates' civic volunteer organization types

ggplot(CC, aes(x=demands))+
  geom_bar(stat="count", width=0.7, fill="steelblue")+
  labs(x = "Civic volunteer organizations' types", y = "Frequencies") +
  geom_text(aes(label=after_stat(count)), stat="count", 
            vjust=1.6, color="white", size=3.5)+
  ggtitle("Figure 2. Delegates' civic volunteer organization types") +
  labs(caption = "Source: Author's own elaboration") + 
  theme(plot.caption = element_text(hjust=0)) +
  theme(text = element_text(size = 12),
        axis.title.y = element_text(size=12),
        axis.title.x = element_text(size=12)) +
  scale_x_discrete(limits=c("Regionalist", "Environmental","Feminist",
                            "Indigenous People","Culture","Human Rights",
                            "Labor","Health","Education","Religion","LGTBIQ+"))

###2.3. Running robust standard errors probability linear models 
###to estimate delegates' volunteer civic organization membership
###Loading package required to run the robust standard error linear models
library("estimatr")

###Models
###Base model
lmsoc0 <- lm(part_socorg ~ pol_ties + RM, data = CC)
summary(lmsoc0)

###Complete model
lmsoc1 <- lm(part_socorg ~ pol_ties + RM +
               age + sex + educ_rec + married, data = CC)
summary(lmsoc1)

###Complete model + robust standard errors clustered by region of the delegates' electoral districts
lmsoc2 <- lm_robust(part_socorg ~ pol_ties + RM +
                      age + sex + educ_rec + married,
                    cluster=RM, data =CC, `se_type` = "stata")
summary(lmsoc2)

###2.4. Ploting regression models: volunteer civic organization membership
###Loading required package
library("modelsummary")

modelsoc <- list("Base model" = lmsoc0,
                 "Compl. Model" = lmsoc1,
                 "Compl. Model + RSE" = lmsoc2)

modelsocdf = modelplot(modelsoc, draw = FALSE) 
table(modelsocdf$term)
modelsocdf<-modelsocdf[!(modelsocdf$term=="(Intercept)" |
                           modelsocdf$term=="age" | 
                           modelsocdf$term=="sexwoman" | 
                           modelsocdf$term=="educ_recLess than postgraduate" |
                           modelsocdf$term=="marriedNot married"),]

modelsocdf$term <- droplevels(modelsocdf$term)

model_colors <- c("Base model" = "#FF9999", 
                  "Compl. Model" = "steelblue", 
                  "Compl. Model + RSE" = "#A0DAA9")

ggsoc <- ggplot(data = modelsocdf, 
                aes(y = term, x = estimate, xmin = conf.low, 
                    xmax = conf.high, color = model)) + 
  geom_pointrange(position = position_dodge(width = 0.7)) +                     
  geom_vline(xintercept=0, colour = gray(1/4), lty = 2) +
  labs(x = "Coefficients", 
       y = "Predictors",
       color = "Models") +
  ggtitle("Figure 3. Probability linear models to predict delegates’ civic volunteer\n organizations membership (95% confidence intervals)") + 
  labs(caption = "Num. obs. Base Model: 155 \nNum. obs. Compl. Model: 147 \nNum. obs. Compl. Model + RSE: 147 \nSource: Author's own elaboration") + 
  theme(plot.caption = element_text(hjust=0)) +
  theme(text = element_text(size = 12),
        axis.title.y = element_text(size=12),
        axis.title.x = element_text(size=12),
        legend.title = element_text(size=10),
        legend.text = element_text(size=10), 
        legend.key.height = unit(0.15, 'cm'),
        legend.key.width = unit(0.15, 'cm')) +
  scale_y_discrete(labels=c("pol_tiesPartisan independent" = "Part. Independent",
                            "pol_tiesNon-partisan independent" = "Non Part. Independent",
                            "RMOther regions" = "Other regions",
                            "RMIndigenous People" = "Indigenous People")) +
  scale_color_manual(values = model_colors) 
ggsoc

####2.5. Estimating linear regression models to predict 
###the years of the social organizations
lm0 <- lm(socorg_old ~ demands,
          data = CC)
summary(lm0)

table(CC$demands)

lm1 <- lm(socorg_old ~ demands + pol_ties + RM + 
            sex + age + educ_rec + married, 
          data = CC)
summary(lm1)

lmROB1 <- lm_robust(socorg_old ~ demands + pol_ties + RM +
                      sex + age + educ_rec + married, 
                    cluster=RM,
                    data=CC, `se_type` = "stata")
summary(lmROB1)

###2.6. Plot regression models
modelyears <- list("Base Model" = lm0,
                   "Compl. Model" = lm1,
                   "Compl. Model + RSE" = lmROB1)

modelyearsdf = modelplot(modelyears, draw = FALSE) 
table(modelyearsdf$term)
modelyearsdf<-modelyearsdf[!(modelyearsdf$term=="(Intercept)" |
                               modelyearsdf$term=="pol_tiesNon-partisan independent" | 
                               modelyearsdf$term=="pol_tiesPartisan independent" | 
                               modelyearsdf$term=="RMIndigenous People" | 
                               modelyearsdf$term=="RMOther regions" | 
                               modelyearsdf$term=="sexwoman" | 
                               modelyearsdf$term=="age" | 
                               modelyearsdf$term=="educ_recLess than postgraduate" |
                               modelyearsdf$term=="marriedNot married"),]

modelyearsdf$term <- droplevels(modelyearsdf$term)

notamet <- "Num obs. Base Model = 500"
model_colors <- c("Base Model" = "#FF9999",   
                  "Compl. Model" = "steelblue", 
                  "Compl. Model + RSE" = "#A0DAA9") 

ggyears <- ggplot(data = modelyearsdf, 
                  aes(y = term, x = estimate, xmin = conf.low, 
                      xmax = conf.high, color = model)) + 
  geom_pointrange(position = position_dodge(width = 0.7)) +                     
  geom_vline(xintercept=0, colour = gray(1/4), lty = 2) +
  labs(x = "Coef.", 
       y = "Predictors",
       color = "Models") +
  ggtitle("Figure 4. Linear regression models to predict the age of delegates’ \n civic volunteer organizations (95% confidence intervals)") +
  labs(caption = "Num. obs. Base Model: 64 \nNum. obs. Compl. Model: 60 \nNum. obs. Compl. Model + RSE: 60\nSource: Author's own elaboration") + 
  theme(plot.caption = element_text(hjust=0)) +
  theme(text = element_text(size = 12),
        axis.title.y = element_text(size=12),
        axis.title.x = element_text(size=12),
        legend.title = element_text(size=10),
        legend.text = element_text(size=10), 
        legend.key.height = unit(0.15, 'cm'),
        legend.key.width = unit(0.15, 'cm')) +
  scale_y_discrete(limits=c("demandsLGTBIQ+","demandsEducation",
                            "demandsHealth","demandsLabor",
                            "demandsHuman Rights","demandsCulture",
                            "demandsIndigenous People","demandsFeminist",
                            "demandsEnvironmental","demandsRegionalist"),
                   labels=c("demandsLGTBIQ+" = "LGTBIQ+",
                            "demandsEducation" = "Education",
                            "demandsHealth" = "Health",
                            "demandsLabor" = "Labor",
                            "demandsHuman Rights" = "Human Rights",
                            "demandsCulture"="Culture",
                            "demandsIndigenous People"="Indigenous People",
                            "demandsFeminist"= "Feminist",
                            "demandsEnvironmental"="Environmental",
                            "demandsRegionalist" = "Regionalist")) +
  scale_color_manual(values = model_colors) 
ggyears


###3. Analysis with the COES' ELSOC Survey----

###Download the COES' ELSOC dataset (long format) from Harvard Dataverse:
###https://dataverse.harvard.edu/dataset.xhtml?persistentId=doi:10.7910/DVN/QZEDUC

###3.1. Cleaning and preparing the dataframe (ELSOC long format)

###Loading requires packages for the analysis
library("foreign")
library("haven")
library("labelled")
library("car")
library("haven")

###Loading the dataset directly from the Harvard Dataverse
url2 <- "https://dataverse.harvard.edu/api/access/datafile/7245116"

# Download the Stata file
download.file(url2, "ELSOC_Long_2016_2022_v1.00.dta", mode = "wb")

# Read the Stata file
elsoc <- read_dta("ELSOC_Long_2016_2022_v1.00.dta")

###ELSOC's waves variable
table(elsoc$ola)
str(elsoc$ola)
##Creation of a new variable based on a recodification of the waves variable
elsoc$rec_ola <- as.factor(elsoc$ola)
elsoc$rec_ola <- dplyr::recode_factor(elsoc$rec_ola,
                                      "1" = "2016",
                                      "2" = "2017",
                                      "3" = "2018",
                                      "4" = "2019",
                                      "5" = "2021",
                                      "6" = "2022") 
table(elsoc$rec_ola)

###Dependent variable: Social movement support
table(elsoc$c20,elsoc$ola)
elsoc$apoyo_movsocs <- as.factor(elsoc$c20)
elsoc$apoyo_movsocs <- dplyr::recode_factor(elsoc$apoyo_movsocs,
                                            "-999" = NA_character_,
                                            "-888" = NA_character_,
                                            "-666" = NA_character_,
                                            "1" = "Student Movement",
                                            "2" = "Labor Movement",
                                            "3" = "Environmental Movement",
                                            "4" = "Indigenous Movement",
                                            "5" = "LGTBIQ+ Movement",
                                            "6" = "Anti-aobortion Movement",
                                            "7" = "Anti-crime Movement",
                                            "8" = "Feminist Movement",
                                            "9" = "No+AFP Movement",
                                            "10" = "Social Outburst Movement",
                                            "11" = "Other movement",
                                            "12" = "None")
table(elsoc$apoyo_movsocs)

###Creating dummy variables for each response related to social movements support
###Support for student movement
elsoc$studmov <- as.numeric(elsoc$apoyo_movsocs)
table(elsoc$studmov)
elsoc$studmov <- car::recode(elsoc$studmov,
                             "1 = 1;
                             2:12 = 0")

###Support for workers' movement
elsoc$labormov <- as.numeric(elsoc$apoyo_movsocs)
table(elsoc$labormov)
elsoc$labormov <- car::recode(elsoc$labormov,
                              "1 = 0;
                              2 = 1;
                              3:12 = 0")

###Support for environmental movement
elsoc$env_mov <- as.numeric(elsoc$apoyo_movsocs)
table(elsoc$env_mov)
elsoc$env_mov <- car::recode(elsoc$env_mov,
                             "1:2 = 0;
                               3 = 1;
                               4:12 = 0")

###Support for indigenous movement
elsoc$indig_mov <- as.numeric(elsoc$apoyo_movsocs)
table(elsoc$indig_mov)
elsoc$indig_mov <- car::recode(elsoc$indig_mov,
                               "1:3 = 0;
                               4 = 1;
                               5:12 = 0")

###Support for LGTBIQ+ movement
elsoc$lgtbiq_mov <- as.numeric(elsoc$apoyo_movsocs)
table(elsoc$lgtbiq_mov)
elsoc$lgtbiq_mov <- car::recode(elsoc$lgtbiq_mov,
                                "1:4 = 0;
                               5 = 1;
                               6:12 = 0")

###Support for feminist movement
elsoc$fem_mov <- as.numeric(elsoc$apoyo_movsocs)
table(elsoc$fem_mov)
elsoc$fem_mov <- car::recode(elsoc$fem_mov,
                             "1:7 = 0;
                               8 = 1;
                               9:12 = 0")
elsoc$fem_mov[elsoc$rec_ola=="2016"] <- NA
elsoc$fem_mov[elsoc$rec_ola=="2017"] <- NA

###Support for No+AFP movement
elsoc$noafp_mov <- as.numeric(elsoc$apoyo_movsocs)
table(elsoc$noafp_mov)
elsoc$noafp_mov <- car::recode(elsoc$noafp_mov,
                               "1:8 = 0;
                               9 = 1;
                               10:12 = 0")
elsoc$noafp_mov[elsoc$rec_ola=="2016"] <- NA
elsoc$noafp_mov[elsoc$rec_ola=="2017"] <- NA

###Social movement support: none
elsoc$nonemov_sup <- as.numeric(elsoc$apoyo_movsocs)
table(elsoc$nonemov_sup)
elsoc$nonemov_sup <- car::recode(elsoc$nonemov_sup,
                                 "1:11 = 0;
                               12 = 1")

###Predictors
###Trust in politics
table(elsoc$c05_01) ##Government
str(elsoc$c05_01)
elsoc$trust_gov <- as.numeric(elsoc$c05_01)
table(elsoc$trust_gov)
elsoc$trust_gov <- car::recode(elsoc$trust_gov,
                               "-999 = NA;
                               -888 = NA;
                               -666 = NA")

table(elsoc$c05_02) ##Political parties
elsoc$trust_polpar <- as.numeric(elsoc$c05_02)
elsoc$trust_polpar <- car::recode(elsoc$trust_polpar,
                                  "-999 = NA;
                                  -888 = NA;
                                  -666 = NA")
table(elsoc$trust_polpar)

table(elsoc$c05_07) ##Parliament
elsoc$trust_parl <- as.numeric(elsoc$c05_07)
elsoc$trust_parl <- car::recode(elsoc$trust_parl,
                                "-999 = NA;
                                  -888 = NA;
                                  -666 = NA")
table(elsoc$trust_parl)

table(elsoc$c05_08) ##President
elsoc$trust_pdnt <- as.numeric(elsoc$c05_08)
elsoc$trust_pdnt <- car::recode(elsoc$trust_pdnt,
                                "-999 = NA;
                                  -888 = NA")
table(elsoc$trust_pdnt)

##Cronbach's Alpha
library("psych")

attach(elsoc)
org_trustpol <- data.frame(trust_gov,trust_polpar,trust_parl,trust_pdnt)
alfa_trustpol <- psych::alpha(org_trustpol)
alfa_trustpol

##Factor analysis
org_trustpol <- na.omit(org_trustpol)
fa_trustpol <- factanal(org_trustpol,
                        factors = 1,
                        rotation = "varimax")

print(fa_trustpol)

###Trust in politics index
elsoc$trustpols <- ((elsoc$trust_parl + elsoc$trust_gov + elsoc$trust_pdnt + elsoc$trust_polpar)/4)
table(elsoc$trustpols)

###Region
table(elsoc$region)
table(elsoc$region_cod)
str(elsoc$region_cod)

elsoc$regions <- elsoc$region_cod
str(elsoc$regions)
table(elsoc$regions)
elsoc$regions <- car::recode(elsoc$regions, 
                             "1:11 = 1;
                        13 = 0;
                        14:16 = 1")

elsoc$regions2 <- as.factor(elsoc$regions)
table(elsoc$regions2)
elsoc$regions2 <- dplyr::recode_factor(elsoc$regions2,
                                       "0" = "Metrop. Region",
                                       "1" = "Other regions")

###Control variables + Respondents' ID
###Respondents' ID variable
str(elsoc$idencuesta)
elsoc$id_rec <- as.factor(elsoc$idencuesta)
str(elsoc$id_rec)

###Control variables
##Sex
table(elsoc$m0_sexo)
str(elsoc$m0_sexo)
elsoc$sex <- as.factor(elsoc$m0_sexo)
elsoc$sex <- dplyr::recode_factor(elsoc$sex,
                                   "1" = "Male",
                                   "2" = "Female")
table(elsoc$sex)

###Education
table(elsoc$m01)
str(elsoc$m01)
elsoc$educ <- as.factor(elsoc$m01)
elsoc$educ <- dplyr::recode_factor(elsoc$educ,
                                   "-999" = NA_character_,
                                   "-888" = NA_character_,
                                   "1" = "Less than primary education",
                                   "2" = "Less than primary education",
                                   "3" = "Primary education",
                                   "4" = "Primary education",
                                   "5" = "Secondary education",
                                   "6" = "Secondary education",
                                   "7" = "Terciary education",
                                   "8" = "Secondary education",
                                   "9" = "Terciary education",
                                   "10" = "Terciary education")
table(elsoc$educ)

###Political ideology 
table(elsoc$c15)
elsoc$ideol <- as.factor(elsoc$c15)
elsoc$ideol <- dplyr::recode_factor(elsoc$ideol,
                                    "-999" = NA_character_,
                                    "-888" = NA_character_,
                                    "-666" = NA_character_,
                                    "0" = "Left",
                                    "1" = "Left",
                                    "2" = "Left",
                                    "3" = "Left",
                                    "4" = "Left",
                                    "5" = "Center",
                                    "6" = "Right",
                                    "7" = "Right",
                                    "8" = "Right",
                                    "9" = "Right",
                                    "10" = "Right",
                                    "11" = "Independent",
                                    "12" = "Independent")
table(elsoc$ideol)
elsoc$ideol <- factor(elsoc$ideol, levels = c("Right","Center","Left","Independent"))

###3.2. Distribution of support for social movement over time
###Generating dataframe without attrition to plot the support for social movement over time
elsoc_sinatr <- elsoc
elsoc_sinatr<-elsoc_sinatr[!is.na(elsoc_sinatr$ponderador_long_panel),]
table(elsoc_sinatr$tipo_atricion)

elsoc$apoyo_movsocs2 <- elsoc$apoyo_movsocs
elsoc$apoyo_movsocs2[elsoc$rec_ola=="2016"&elsoc$apoyo_movsocs2=="Feminist Movement"] <- NA
elsoc$apoyo_movsocs2[elsoc$rec_ola=="2016"&elsoc$apoyo_movsocs2=="No+AFP Movement"] <- NA
table(elsoc$rec_ola,elsoc$apoyo_movsocs2)

ssmm_2 <- table(elsoc_sinatr$rec_ola,elsoc_sinatr$apoyo_movsocs)
ssmm_2
ssmm_2 <- as.matrix(ssmm_2)
ssmm_2prop <- prop.table(ssmm_2,margin = 1)
ssmm_2prop <- as.data.frame(ssmm_2prop)
ssmm_2prop

ssmm_2prop2 <- ssmm_2prop
table(ssmm_2prop2$Var2)
ssmm_2prop2<-ssmm_2prop2[!(ssmm_2prop2$Var2=="Anti-aobortion Movement" | 
                             ssmm_2prop2$Var2=="Anti-crime Movement" | 
                             ssmm_2prop2$Var2=="Social Outburst Movement" | 
                             ssmm_2prop2$Var2=="Other movement"),]

ssmm_2prop2$Var2 <- droplevels(ssmm_2prop2$Var2)
table(ssmm_2prop2$Var2)

ssmm_2prop2$Var2 <- dplyr::recode_factor(ssmm_2prop2$Var2, 
                                  "Labor Movement" = "Workers' Movement")

ssmm_2prop2$Var2 <- factor(ssmm_2prop2$Var2, 
                           levels=c("Student Movement",
                                    "Workers' Movement",
                                    "Environmental Movement",
                                    "Indigenous Movement",
                                    "LGTBIQ+ Movement",
                                    "Feminist Movement",
                                    "No+AFP Movement",
                                    "None"))

table(ssmm_2prop2$Var2)

ssmm_2prop2$Freq <- car::recode(ssmm_2prop2$Freq,
                                "0 = NA")
table(ssmm_2prop2$Freq)

###Plot the distribution of the support for social movements over time
ggplot(data = ssmm_2prop2, 
       (aes(x = Var1,
            y = Freq,
            group = Var2))) +
  geom_line(size = 2, color = "steelblue") + 
  geom_point(size = 3, color = "steelblue") +
  geom_vline(xintercept="2019", colour = gray(1/4), lty = 2) +
  labs(x = "Survey Wave (year)", 
       y = "Support for Social Movements (%)") +
  guides(col = FALSE) +
  ggtitle("Figure 5. Individual support for social movements over the survey’s waves") +
  labs(caption = "Source: Author's own elaboration based on ELSOC-COES (2016-2022)") + 
  theme(plot.caption = element_text(hjust=0)) +
  facet_wrap(Var2~., ncol = 4)

###3.3. Estimating individual fixed effect linear models probability models
###to predict support for social movements
lmROB_stud <- lm_robust(studmov ~ rec_ola + sex + m0_edad + ideol + educ +
                            trustpols +
                            regions2, 
                          fixed_effects = ~ id_rec,
                          data = elsoc_sinatr, 
                          cluster=region_cod, se_type = "stata",
                          weights = ponderador_long_panel)
summary(lmROB_stud)

lmROB_lab <- lm_robust(labormov ~ rec_ola + sex + m0_edad + ideol + educ +
                           trustpols +
                           regions2, 
                         fixed_effects = ~ id_rec, 
                         data = elsoc_sinatr,
                         cluster=region_cod, se_type = "stata",
                         weights = ponderador_long_panel)
summary(lmROB_lab)

lmROB_env <- lm_robust(env_mov ~ rec_ola + sex + m0_edad + ideol + educ +
                           trustpols +
                           regions2, 
                         fixed_effect = ~ id_rec,
                         data = elsoc_sinatr,
                         cluster=region_cod, se_type = "stata",
                         weights = ponderador_long_panel)
summary(lmROB_env)

lmROB_indig <- lm_robust(indig_mov ~ rec_ola + sex + m0_edad + ideol + educ +
                             trustpols +
                             regions2, 
                           fixed_effects = ~ id_rec,
                           data = elsoc_sinatr,
                           cluster=region_cod, se_type = "stata",
                           weights = ponderador_long_panel)
summary(lmROB_indig)

lmROB_lgtbiq <- lm_robust(lgtbiq_mov ~ rec_ola + sex + m0_edad + ideol + educ +
                              trustpols +
                              regions2, 
                            fixed_effects = ~ id_rec,
                            data = elsoc_sinatr,
                            cluster=region_cod, se_type = "stata",
                            weights = ponderador_long_panel)
summary(lmROB_lgtbiq)

lmROB_fem <- lm_robust(fem_mov ~ rec_ola + sex + m0_edad + ideol + educ +
                           trustpols + 
                           regions2, 
                         fixed_effects = ~ id_rec,
                         data = elsoc_sinatr,
                         cluster=region_cod, se_type = "stata",
                         weights = ponderador_long_panel)
summary(lmROB_fem)

lmROB_noafp <- lm_robust(noafp_mov ~ rec_ola + sex + m0_edad + ideol + educ +
                             trustpols +
                             regions2, 
                           fixed_effects = ~ id_rec,
                           data = elsoc_sinatr,
                           cluster=region_cod, se_type = "stata",
                           weights = ponderador_long_panel)
summary(lmROB_noafp)

###3.4. Plot the regression models
##student movement
modelstud <- list("Complete model" = lmROB_stud)
modelstuddf = modelplot(modelstud, draw = FALSE)
modelstuddf <- modelstuddf[c(1,2,3,4,5,14,15),] 
modelstuddf$term <- droplevels(modelstuddf$term)
table(modelstuddf$term)

###Workers' movement
modellab <- list("Complete model" = lmROB_lab)
modellabdf = modelplot(modellab, draw = FALSE)
modellabdf <- modellabdf[c(1,2,3,4,5,14,15),] 
modellabdf$term <- droplevels(modellabdf$term)
table(modellabdf$term)

###Environmental movement
modelenv <- list("Complete model" = lmROB_env)
modelenvdf = modelplot(modelenv, draw = FALSE)
modelenvdf <- modelenvdf[c(1,2,3,4,5,14,15),] 
modelenvdf$term <- droplevels(modelenvdf$term)
table(modelenvdf$term)

###Indigenous Movement
modelindig <- list("Complete model" = lmROB_indig)
modelindigdf = modelplot(modelindig, draw = FALSE) 
modelindigdf <- modelindigdf[c(1,2,3,4,5,14,15),] 
modelindigdf$term <- droplevels(modelindigdf$term)
table(modelindigdf$term)

###LGTBIQ+ Movement
modellgtbiq <- list("Complete model" = lmROB_lgtbiq)
modellgtbiqdf = modelplot(modellgtbiq, draw = FALSE) 
modellgtbiqdf <- modellgtbiqdf[c(1,2,3,4,5,14,15),] 
modellgtbiqdf$term <- droplevels(modellgtbiqdf$term)
table(modellgtbiqdf$term)

###Feminist Movement
modelfem <- list("Complete model" = lmROB_fem)
modelfemdf = modelplot(modelfem, draw = FALSE) 
modelfemdf <- modelfemdf[c(1,2,3,12,13),] 
modelfemdf$term <- droplevels(modelfemdf$term)
table(modelfemdf$term)

###No+AFP Movement
modelnoafp <- list("Complete model" = lmROB_noafp)
modelnoafpdf = modelplot(modelnoafp, draw = FALSE) 
modelnoafpdf <- modelnoafpdf[c(1,2,3,12,13),] 
modelnoafpdf$term <- droplevels(modelnoafpdf$term)
table(modelnoafpdf$term)

modelstuddf$movement <- "Student Movement"
modellabdf$movement <- "Workers' Movement"
modelenvdf$movement <- "Environmental Movement"
modelindigdf$movement <- "Indigenous Movement"
modellgtbiqdf$movement <- "LGTBIQ+ Movement"
modelfemdf$movement <- "Feminist Movement"
modelnoafpdf$movement <- "No+AFP Movement"

modeltodosdf <- rbind(modelstuddf,modellabdf,modelenvdf,modelindigdf,
                      modellgtbiqdf,modelfemdf,modelnoafpdf)

table(modeltodosdf$term)
str(modeltodosdf$term)
modeltodosdf$term <- dplyr::recode_factor(modeltodosdf$term,
                                          "rec_ola2017" = "Wave 2017",
                                          "rec_ola2018" = "Wave 2018",
                                          "rec_ola2019" = "Wave 2019",
                                          "rec_ola2021" = "Wave 2021",
                                          "rec_ola2022" = "Wave 2022",
                                          "trustpols" = "Trust in politics",
                                          "regions2Other regions" = "Other regions")

modeltodosdf$movement <- factor(modeltodosdf$movement, 
                                levels=c("Student Movement","Workers' Movement",
                                         "Environmental Movement",
                                         "Indigenous Movement",
                                         "LGTBIQ+ Movement",
                                         "Feminist Movement",
                                         "No+AFP Movement"))

ggplot(modeltodosdf, aes(x = term, y = estimate)) +
  geom_hline(yintercept = 0, colour = gray(1/4), lty = 2) +
  geom_point(aes(x = term, y = estimate), color = "steelblue") + 
  geom_linerange(aes(x = term, 
                     ymin = conf.low,
                     ymax = conf.high),
                 lwd = 1, color = "steelblue") + 
  labs(x = "Predictors", y = "Coefficients") +
  theme(text = element_text(size = 12),
        axis.title.y = element_text(size=12),
        axis.title.x = element_text(size=12),
        legend.title = element_text(size=10),
        legend.text = element_text(size=10), 
        legend.key.height = unit(0.15, 'cm'),
        legend.key.width = unit(0.15, 'cm')) +
  ggtitle("Figure 6. Individual fixed effect linear probability models to predict \nsupport for social movements (95% confident intervals)") +
  labs(caption = "\nNote: Models were built using weights that considered the sample without attrition; the weights were constructed by the \nELSOC-COES' research team.
                 \nNum. obs. of all models except Feminist and No+AFP Movements Models: 9735 \nNum. obs. Feminist and No+AFP Movements Model: 7244 \nSource: Author's own elaboration") + 
  theme(plot.caption = element_text(hjust=0)) +
  scale_x_discrete(limits=c("Other regions",
                            "Trust in politics","Wave 2022",
                            "Wave 2021","Wave 2019",
                            "Wave 2018","Wave 2017")) +
  coord_flip() +
  facet_wrap(movement~., ncol = 2)


###4. Appendix (A2 and A3)----
library("modelsummary")

###Generating regression models table related to probability linear models to predict 
###delegates' civic volunteer organizations membership (table A2.4 of the Appendix A2)
modelsummary(list("Base Model" = lmsoc0,
                  "Compl. Model" = lmsoc1, 
                  "Compl. Model + RSE" = lmsoc2), 
             stars = TRUE, 
             statistic = "std.error",
             output = "C:/Users/rozas/OneDrive/Escritorio/Joaquín/Doctorado - UPF/Thesis/Papers/Paper 2 - CC/Paper PS Politics & Political Science/Accepted paper/tableA2.4.docx")
        ###In the "output" part of the code, specify the desired location on your
        ###computer to download and save the docx file

###Generating the regression models table related to linear regression models to predict
###the age of delegates' civic volunteer organizations (table A2.5 of the Appendix A2)
modelsummary(list("Base Model" = lm0,
                  "Compl. Model" = lm1,
                  "Compl. Model + RSE" = lmROB1), 
             stars = TRUE, 
             statistic = "std.error",
             output = "C:/Users/rozas/OneDrive/Escritorio/Joaquín/Doctorado - UPF/Thesis/Papers/Paper 2 - CC/Paper PS Politics & Political Science/Accepted paper/tableA2.5.docx")
###In the "output" part of the code, specify the desired location on your
###computer to download and save the docx file


###Generating the regression models table related to individual fixed effect probability 
###linear models to predict support for social movements (table A3.4 of the Appendix A3)
modelsummary(list("M1: Student Mov." = lmROB_stud,
                  "M2: Workers Mov." = lmROB_lab, 
                  "M3: Environmental Mov." = lmROB_env,
                  "M4: Indigenous Mov." = lmROB_indig,
                  "M5: LGTBIQ+ Mov." = lmROB_lgtbiq,
                  "M6: Feminist Mov." = lmROB_fem,
                  "M7: No+AFP Mov." = lmROB_noafp), 
             stars = TRUE, 
             statistic = "std.error",
             output = "C:/Users/rozas/OneDrive/Escritorio/Joaquín/Doctorado - UPF/Thesis/Papers/Paper 2 - CC/Paper PS Politics & Political Science/Accepted paper/tableA3.4.docx")
###In the "output" part of the code, specify the desired location on your
###computer to download and save the docx file
